﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Users;
using EntitySpaces.DynamicQuery;

namespace DNNspot.LiveChat
{
    public partial class EditAgent : ModuleBase
    {
        private int? _agentId;

        // ### EVENTS ######################################################

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                LoadSettings();
                LoadControls();
            }

            LoadAgentId();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Redirect();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
            Redirect();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Save();
            Redirect();
        }

        // ### PRIVATE FUNCTIONS ###########################################

        private void Delete()
        {
            var agent = Agent.Load(_agentId);
            agent.MarkAsDeleted();
            agent.Save();
        }

        private void LoadAgentId()
        {
            _agentId = null;

            if (Convert.ToInt32(hidAgentId.Value) > -1)
                _agentId = Convert.ToInt32(hidAgentId.Value);
        }

        private void LoadAgentsDropDownList()
        {
            var userIds = new List<int>();
            var userId = Agent.Load(_agentId).UserId;
            var agents = new AgentCollection();
            agents.LoadAll();

            foreach (Agent agent in agents)
                if (agent.UserId != userId)
                    userIds.Add(Convert.ToInt32(agent.UserId));

            var q = new UserQuery();
            
            if(userIds.Count > 0)
                q.Where(q.UserID.NotIn(userIds));
            
            q.OrderBy(q.LastName.Ascending, q.FirstName.Ascending, q.Username.Ascending);

            var users = new UserCollection();
            users.Load(q);

            foreach (User user in users)
                ddlDNNUsers.Items.Add(new ListItem(string.Format("{0}, {1} ({2})", user.LastName, user.FirstName, user.Username), user.UserID.ToString()));
        }

        private void LoadControls()
        {
            LoadAgentId();

            LoadAgentsDropDownList();

            var userId = Agent.Load(_agentId).UserId;

            if (ddlDNNUsers.Items.FindByValue(userId.ToString()) != null)
                ddlDNNUsers.Items.FindByValue(userId.ToString()).Selected = true;

            if (_agentId != null)
                btnDelete.Visible = true;
        }

        private void LoadSettings()
        {
            _agentId = Convert.ToInt32(Request.QueryString[Params.AgentId]);
            hidAgentId.Value = _agentId.ToString();
        }

        private void Redirect()
        {
            Response.Redirect(Globals.NavigateURL(TabId));
        }

        private void Save()
        {
            var agent = Agent.Load(_agentId);
            agent.PortalId = PortalId;
            agent.UserId = Convert.ToInt32(ddlDNNUsers.SelectedValue);
            agent.Save();
        }
    }
}